<template>
	<view class="page-box">
		<view class="form-card">
			<u-form :model="formData" :rules="rules" ref="formRef">


				<!-- 昵称 -->
				<u-form-item label="昵称" prop="nickname" label-width="100">
					<u-input v-model="formData.nickname" placeholder="请输入昵称" clearable />
				</u-form-item>

				<!-- 手机号 -->
				<u-form-item label="手机号" prop="phoneNum" label-width="100">
					<u-input v-model="formData.phoneNum" placeholder="请输入手机号" clearable />
				</u-form-item>

				<!-- 性别 -->
				<u-form-item label="性别" prop="sex">
					<u-radio-group v-model="formData.sex">
						<u-radio :name="0">男</u-radio>
						<u-radio :name="1">女</u-radio>
						<u-radio :name="2">其他</u-radio>
					</u-radio-group>
				</u-form-item>

				<!-- 头像上传 -->
				<u-form-item label-width="auto" label="上传头像:" prop="image">
					<u-upload ref="imgUploadRef" :action="action" :file-list="fileList" @on-change="onChange"
						@on-remove="onRemove" max-count="1"></u-upload>
				</u-form-item>
			</u-form>
		</view>

		<view class="footer">
			<u-button type="primary" shape="circle" :loading="loading" @click="submitForm">
				保存信息
			</u-button>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		editUserApi,
		getUserInfoApi

	} from '@/api/user'
	import http from '../../common/http/http.js'


	const formRef = ref(null)
	const loading = ref(false)
	const avatarList = ref([])

	const formData = reactive({
		userId: uni.getStorageSync('userId'),
		nickname: '',
		avatar: '',
		phoneNum: '',
		sex: 0,

	})

	const rules = {
		nickname: {
			required: true,
			message: '请输入昵称',
			trigger: ['blur']
		},
		phoneNum: {
			required: true,
			message: '请输入手机号',
			trigger: ['blur']
		},
		sex: {
			required: true,
			message: '请选择性别',
			trigger: ['change']
		},
		avatar: {
			required: true,
			message: '请上传头像',
			trigger: ['blur']
		}
	}


	// 获取用户信息
	const fetchUserInfo = async () => {
		try {
			const userId = uni.getStorageSync('userId')
			const res = await getUserInfoApi(userId)

			if (res && res.code === 200) {
				console.log(res.data)
				Object.assign(formData, res.data)
			}
		} catch (error) {
			console.error(error)
		}
	}


	const imgUploadRef = ref()
	const fileList = ref([])
	const action = ref(http.baseUrl + "/api/upload/image")
	// 使用空数组存储图片路径,然后用push存入
	const imageUrls = ref([])
	// 图片上传触发
	const onChange = (e) => {
		// console.log("onChange",e)
		// onChange {statusCode: 200, data: "{"msg":"upload success","code":200,"data":"/develop/image/f72ecdd8-b204-43e9-9a81-0703cca22361.png"}", header: {…}, cookies: Array(0), errMsg: "uploadFile:ok"}cookies: []data: "{"msg":"upload success","code":200,"data":"/develop/image/f72ecdd8-b204-43e9-9a81-0703cca22361.png"}"errMsg: "uploadFile:ok"header: {Content-Type: "application/json", Transfer-Encoding: "chunked", Date: "Mon, 17 Mar 2025 01:51:58 GMT", Keep-Alive: "timeout=60", Connection: "keep-alive"}statusCode: 200__proto__: Object
		// console.log(e.data.data)
		// undefined 直接访问 e.data.data 得不到结果，因为 e.data 是一个字符串，而不是对象。
		// console.log(e.data)
		// {"msg":"upload success","code":200,"data":"/develop/image/b69590b5-3e79-482e-a859-b0a716ab8a2b.png"}
		// 使用 JSON.parse() 将 JSON 格式的字符串转换为 JavaScript 对象后，才能访问其中的属性。
		let imgRes = JSON.parse(e.data)
		// console.log(imgRes.data)
		// /develop/image/50b12d56-814a-4762-ac53-21e464644136.png
		// 将图片路径存入数组
		// console.log(http.baseUrl)
		imageUrls.value.push(http.baseUrl + imgRes.data)
		// 把数组中的图片转换为逗号分隔的字符串
		// http://localhost:8089
		let url = ""
		for (let i = 0; i < imageUrls.value.length; i++) {
			url = url + imageUrls.value[i] + ","
		}
		// console.log(url)
		// http://localhost:8089/develop/image/afcddf95-c801-4c60-8f6a-f019b025b6e7.jpg,http://localhost:8089/develop/image/4d71931d-c24e-4680-bc70-0ced02e9000a.jpg,http://localhost:8089/develop/image/88ae2346-fa2c-45eb-b2b0-4766bfb4887a.jpg,
		// 去掉最后一个逗号
		formData.avatar = url.substring(0, url.length - 1)
		console.log(formData)
		// console.log(formData.avatar)

	}
	// 图片移除
	const onRemove = (index) => {
		// console.log(index)
		imageUrls.value.splice(index, 1)
		let url = ""
		for (let i = 0; i < imageUrls.value.length; i++) {
			url = url + imageUrls.value[i] + ","
		}
		// 去掉最后一个逗号
		formData.avatar = url.substring(0, url.length - 1)
		console.log(formData)

	}

	const submitForm = () => {
		formRef.value.validate().then(async () => {
			loading.value = true
			try {
				const res = await editUserApi(formData)
				uni.showToast({
					title: res.code === 200 ? '保存成功' : res.msg || '保存失败',
					icon: res.code === 200 ? 'success' : 'none'
				})
				if (res.code === 200) {
					setTimeout(() => uni.navigateBack(), 1500)
				}
			} finally {
				loading.value = false
			}
		})
	}
	// onShow
	onMounted(() => {
		fetchUserInfo()
	})
</script>

<style lang="scss" scoped>
	.page-box {
		padding: 30rpx;
		background-color: #f7f7f7;
		min-height: 100vh;
	}

	.form-card {
		background: #fff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);
		padding-bottom: 20rpx;
	}

	.footer {
		padding: 60rpx 30rpx 0;

		.u-button {
			height: 90rpx;
			font-size: 32rpx;
		}
	}
</style>